﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace NFramework.DataAccess
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly")]
    public class StructuredResultHelper : DataHelper<StructuredResultHelper>, IStructuredResultHelper
    {
        bool IsGettingSchema { get; set; }

        #region [ IStructuredResultHelper Members ]

        private System.Data.Common.DbDataAdapter GetAdapter()
        {
            System.Data.Common.DbDataAdapter adapter = null;
            if (adapter == null)
            {
                var localCommand = Command as System.Data.SqlClient.SqlCommand;
                if (localCommand != null) { adapter = new System.Data.SqlClient.SqlDataAdapter(localCommand); }
            }
            if (adapter == null)
            {
                var localCommand = Command as System.Data.Odbc.OdbcCommand;
                if (localCommand != null) { adapter = new System.Data.Odbc.OdbcDataAdapter(localCommand); }
            }
            if (IsGettingSchema) { adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; }
            return adapter;
        }

        public System.Data.DataTable GetDataTable()
        {
            return ExecuteHelper<DataTable>(() =>
            {
                var result = new DataTable();
                var adapter = GetAdapter();
                adapter.Fill(result);
                return result;
            } );
        }

        public System.Data.DataSet GetDataSet()
        {
            return GetDataSet(new DataSet());
        }

        public System.Data.DataSet GetDataSet(System.Data.DataSet dataSetToFill)
        {
            return ExecuteHelper<DataSet>(() =>
            {
                var adapter = GetAdapter();
                adapter.Fill(dataSetToFill);
                return dataSetToFill;
            });
        }

        #endregion
    }
}
